﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using SharedLibraries;
using SharedLibraries.Constants;
using EntityObject;
using DataAccessObject;
using ThangNM_LIB.FUNC;
using ThangNM_LIB.DB;

namespace ThangNM.UserControl
{
    public partial class Category_ListUC : System.Web.UI.UserControl
    {
        #region "Properties & Event"
        public delegate void CustomerEventHandler(object sender, CustomerEventArgs args);
        public event CustomerEventHandler ViewDetail;
        public event CustomerEventHandler ViewMessage;
        public event EventHandler Insert;

        public SortDirection directionState
        {
            get { return (ViewState["directionState"] == null ? SortDirection.Descending : (SortDirection)ViewState["directionState"]); }
            set { ViewState["directionState"] = value; }
        }
        //public Boolean bStatus
        //{
        //    get { return (ViewState["bStatus"] == null ? false : (Boolean)ViewState["bStatus"]); }
        //    set { ViewState["bStatus"] = value; }
        //}
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ToolBarUC1.ViewGroupButtonByFunction(ConstEx.funcButtonToolBar.LIST);
                ToolBarUC1.BindData_DropDownList(GetListConstants.Category_bStatus_GLC());
                ToolBarUC1.SetDefaultValue(true);
                BindData_List(null);
            }
        }

        public void BindData_List(String sSortColumn)
        {
            try
            {
                List<Category_ZipEO> lst = new List<Category_ZipEO>();
                grvList.Visible = false;
                string keysearch = StringEx.Trim(SearchUI1.txtTextSearch.Text).ToUpper();
                DataTable dt = (new CategoryDAO()).SelectBy_bStatus(Convert.ToBoolean(ToolBarUC1.ddlStatus.SelectedValue));
                DataView dv = dt.DefaultView;
                if (!String.IsNullOrEmpty(sSortColumn))
                    dv.Sort = sSortColumn;
                else
                    dv.Sort = "[PK_iCategoryID] DESC";
                dt = dv.ToTable();
                var result = (List<Category_ZipEO>)ConvertEx.ConvertDataTableToListObject<Category_ZipEO>(dt, lst.GetType());
                //var result = (from p in CustomerCache.get_lstCategory_ZipEO()
                //              where StringEx.Equals(ToolBarUC1.ddlStatus.SelectedValue, Convert.ToString(p.bStatus))
                //              select p).ToList();
                if (result != null)
                {
                    if (SearchUI1.ddlTypeSearch.SelectedValue.Equals("0"))
                    {
                        if (!String.IsNullOrEmpty(keysearch))
                        {
                            result = result.FindAll(x => StringEx.CompareEx(x.PK_iCategoryID.ToString(),keysearch));
                        }
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(keysearch))
                        {
                            result = result.FindAll(x => StringEx.CompareEx(x.sName,keysearch));
                        }
                    }
                    if (result.Count() > 0)
                    {
                        grvList.Visible = true;
                        grvList.DataSource = result.ToList();
                        grvList.DataBind();
                        lblRowCount.Text = MessagesEx.Tong_So_Ban_Ghi + result.Count();
                        return;
                    }
                }
                grvList.DataSource = null;
                grvList.DataBind();
                lblRowCount.Text = MessagesEx.Khong_Thoa_Man_Dieu_Kien_Tim_Kiem;
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        public void ResetFormSearch()
        {
            SearchUI1.txtTextSearch.Text = "";
            SearchUI1.ddlTypeSearch.SelectedValue = "0";
        }

        #region "Event Handler"
        protected void Search_Click(object sender, EventArgs e)
        {
            BindData_List(null);
        }

        protected void EventButtonToolBar_Click(object sender, CustomerEventArgs e)
        {
            if ((new ShareDAO.UserDAO()).SelectBy_sPermission(Session["secret"], Convert.ToString(Request.Url.AbsolutePath), e.iType) == false)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.DANGER, MessagesEx.Khong_Co_Quyen_Truy_Cap, null));
                Commons.setAccessDenied(Page, null);
                return;
            }
            switch (e.iType)
            {
                case ConstEx.funcButtonToolBar.INSERT_LIST:
                    if (Insert != null)
                        Insert(this, EventArgs.Empty);
                    break;
                case ConstEx.funcButtonToolBar.INSERT_ITEM: break;
                case ConstEx.funcButtonToolBar.UPDATE_ITEM: break;
                case ConstEx.funcButtonToolBar.DELETE_LIST:
                    DeleteList();
                    break;
                case ConstEx.funcButtonToolBar.DELETE_ITEM: break;
                case ConstEx.funcButtonToolBar.REFRESH_LIST:
                    ResetFormSearch();
                    BindData_List(null);
                    break;
                case ConstEx.funcButtonToolBar.EXPORT_EXCEL:
                    if (grvList.PageCount > 0)
                    {
                        ExportEx.PDF_Export(grvList, "Category");
                    }
                    else
                    {
                        setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, "Không thể xuất file vì không có bản ghi nào.", null));
                    }
                    break;
                case ConstEx.funcButtonToolBar.RESET_FORM: break;
            }
        }

        protected void EventSelectChange_Click(object sender, CustomerEventArgs e)
        {
            if (e != null)
            {
                BindData_List(null);
            }
        }
        #endregion

        #region "Event GridView"
        protected void grvList_RowCommand(object source, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "cmdView")
            {
                int rowIndex = Convert.ToInt32(e.CommandArgument) % grvList.PageSize;
                Int16 PK_iCategorysID = Convert.ToInt16(grvList.DataKeys[rowIndex].Values[0]);
                CategoryEO _CategoryEO = new CategoryEO();
                _CategoryEO = (new CategoryDAO()).SelectItem(PK_iCategorysID);
                if (ViewDetail != null)
                    ViewDetail(this, new CustomerEventArgs(1, "Oki", _CategoryEO));
            }
        }

        protected void grvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvList.PageIndex = e.NewPageIndex;
            BindData_List(null);
        }

        protected void grvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (directionState == SortDirection.Ascending)
            {
                directionState = SortDirection.Descending;
                BindData_List("[" + e.SortExpression + "]" + " DESC");
            }
            else
            {
                directionState = SortDirection.Ascending;
                BindData_List("[" + e.SortExpression + "]" + " ASC");
            }
        }
        #endregion

        protected void DeleteList()
        {
            try
            {
                string strID = "";
                string strName = "";
                foreach (GridViewRow row in grvList.Rows)
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkItem");
                    if (chk != null && chk.Checked)
                    {
                        strID += "," + grvList.DataKeys[row.RowIndex].Values["PK_iCategoryID"];
                        strName += "," + System.Configuration.ConfigurationManager.AppSettings["HOMEPAGE"] + FileNameByFunction.Danh_Muc_ + RewriteUrl.ConvertToUnSign(Convert.ToString(grvList.DataKeys[row.RowIndex].Values["sName"])) + "." + Convert.ToString(grvList.DataKeys[row.RowIndex].Values["PK_iCategoryID"]) + FileNameByFunction.HTML;
                    }
                }
                if (String.IsNullOrEmpty(strID))
                {
                    setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.CHUA_CHON_DONG_NAO_DE_XOA, ConstEx.Table_Name_C.Account), null));
                    return;
                }
                //if (CategoryDAO.Delete(strID.Substring(1), strName.Substring(1)))
                //{
                //    BindData_List(null);
                //    if (ViewMessage != null)
                //    {
                //        ViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Xoa_Thanh_Cong_Ma, ConstEx.Table_Name_C.Category, strID.Substring(1)), null));
                //    }
                //}
                //else
                //{
                //    if (ViewMessage != null)
                //    {
                //        ViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Xoa_That_Bai_Ma, ConstEx.Table_Name_C.Category, strID.Substring(1)), null));
                //    }
                //}
            }
            catch (Exception ex)
            {
                setViewMessage(this, new CustomerEventArgs(ConstEx.FunctionSetMsg.ERROR, ex.Message, null));
            }
        }

        public void setViewMessage(object sender, CustomerEventArgs args)
        {
            if (ViewMessage != null)
                ViewMessage(sender, args);
        }
    }
}